package openhaven.control.net;

import java.io.UnsupportedEncodingException;

/**
 * Basically a copy of haven.Utils but with only the bit fiddling stuff so as to
 * avoid a massive dependency tree.
 */
public class BitFiddlingUtils
{
    public static byte sb(final int b)
    {
        if (b > 127)
        {
            return ((byte) (-256 + b));
        }
        else
        {
            return ((byte) b);
        }
    }

    public static void uint16e(final int num, final byte[] buf, final int off)
    {
        buf[off] = sb(num & 0xff);
        buf[off + 1] = sb((num & 0xff00) >> 8);
    }

    public static void int32e(final int num, final byte[] buf, final int off)
    {
        if (num < 0)
        {
            uint32e(0x100000000L + (num), buf, off);
        }
        else
        {
            uint32e(num, buf, off);
        }
    }

    static void uint32e(final long num, final byte[] buf, final int off)
    {
        buf[off] = sb((int) (num & 0xff));
        buf[off + 1] = sb((int) ((num & 0xff00) >> 8));
        buf[off + 2] = sb((int) ((num & 0xff0000) >> 16));
        buf[off + 3] = sb((int) ((num & 0xff000000) >> 24));
    }

    static int ub(final byte b)
    {
        if (b < 0)
        {
            return (256 + b);
        }
        else
        {
            return (b);
        }
    }

    static int uint16d(final byte[] buf, final int off)
    {
        return (ub(buf[off]) + (ub(buf[off + 1]) * 256));
    }

    static int int32d(final byte[] buf, final int off)
    {
        final long u = uint32d(buf, off);
        if (u > Integer.MAX_VALUE)
        {
            return ((int) ((((long) Integer.MIN_VALUE) * 2) - u));
        }
        else
        {
            return ((int) u);
        }
    }

    static long uint32d(final byte[] buf, final int off)
    {
        return (ub(buf[off]) + (ub(buf[off + 1]) * 256) + (ub(buf[off + 2]) * 65536) + (ub(buf[off + 3]) * 16777216));
    }

    static String strd(final byte[] buf, final int[] off)
    {
        int i;
        for (i = off[0]; buf[i] != 0; i++)
        {
            ;
        }
        String ret;
        try
        {
            ret = new String(buf, off[0], i - off[0], "utf-8");
        }
        catch (final UnsupportedEncodingException e)
        {
            throw (new RuntimeException(e));
        }
        off[0] = i + 1;
        return (ret);
    }
}
